<?php

namespace Admin\Frontend\Controllers;

use Helpers\File;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\UserPower;
use Helpers\Tool;
use Phalcon\Mvc\Controller;
use Phalcon\Db\Adapter\Pdo\Mysql;
class WordController extends Controller
{

    function getConfig()
    {
        static $config;
        if(!$config){
            $config = Main::getConfigByName('examExport');
        }
        return $config;
    }

    function createMailErrLog($msg)
    {
        if($msg !== true) {
            $examId = $this->request->getPost('examId', 'int');
            Main::createCommitLog('word', 'exam', 'mailError', $this->request->getPost(), $examId, '邮件发送失败:' . $msg);
        }
    }

    /**
     * 导出题库为word主程序
     *
     * create by ck 20170504
     * modify by ck 20170605    邮件发送失败则上传文件服务器
     */
    public function exportExamToFileAction()
    {
        //测试数据
        set_time_limit(0);
        ignore_user_abort(true);
        $this->view->disable();
        $t1 = microtime(true);

        $examId = $this->request->getPost('examId', 'int');
        $adId = $this->request->getPost('adId', 'int');
        $address = $this->request->getPost('address', 'email');
        $examId or die('缺少题库ID');
        $address or die('缺少邮箱地址');

//        $path = rtrim($this->getConfig()['savePath'], '/') . '/' . $examId;
        $path = TEMP_PATH . '/' . $examId;
        if(!(is_dir($path) || mkdir($path, 0777, true))){
            die($path . '目录创建失败！');
        }
        $config = Main::getConfigByName('oldCenterDB');
//        $config['dbname'] = 'xh_product_exam' . $examId;
        $config['dbname'] .= '_exam' . $examId;
        $conn = new Mysql($config);

        Main::createCommitLog('word', 'exam', 'export', $this->request->getPost(), $examId, '开始导出');
        if($adId){
            $sourceQuestionArr = $conn->fetchAll("select ho_zycontent as sQueContent,ho_zytype as iQueType,ho_answer as sAnswer,ho_id,ho_zytype from homework_list_base WHERE ho_parent_id = 0 and ho_ad_id = {$adId} order by ho_ord");
            $questionArr = [];
            foreach($sourceQuestionArr as $question){
                $questionArr[] = $question;
                if($question['ho_zytype'] == 6){
                    $childArr = $conn->fetchAll("select ho_zycontent as sQueContent,ho_zytype as iQueType,ho_answer as sAnswer from homework_list_base WHERE ho_parent_id = {$question['ho_id']} and ho_ad_id = {$adId} order by ho_ord");
                    foreach($childArr as $child){
                        $questionArr[] = $child;
                    }
                }
            }
            unset($sourceQuestionArr);
            if(!$questionArr){
                die('该目录下无题目数据');
            }
            $url = $this->createWord('test', $questionArr);
            if(!is_string($url)){
                Main::createCommitLog('word', 'exam', 'mailError', ['post'=>$this->request->getPost(), 'wordResponse' => $url], $examId, '导出失败');
                $result = Tool::sendMsgToMail($address, [
                    'title'     => '题库word文件-' . $examId . '-失败',
                    'content'   => json_encode($url, JSON_UNESCAPED_UNICODE)
                ]);
                $this->createMailErrLog($result);
                die;
            }
            Main::createCommitLog('word', 'exam', 'export', $url, $examId, '导出题库');
            $result = Tool::sendMsgToMail($address, [
                'title'     => '题库word文件-' . $examId . '-成功',
                'content'   => '下载地址：' . $url
            ]);
            $this->createMailErrLog($result);
            die;
        }

        //获取目录，组成树结构
        $titleArr = $conn->fetchAll("select ad_id,ad_name,ad_parentid from address_items_tree_user");
        $titleArr or die('该题库下无目录');
        $tree = [];
        $this->dealTree($tree, $titleArr);
        $this->dealWord($tree, $conn);
        $this->saveWord($tree, $path);
        $result = Tool::createZipFile($path . '.zip', $path);
        if(is_string($result)){
            Main::createCommitLog('word', 'exam', 'exportError', json_encode($tree, JSON_UNESCAPED_UNICODE), $examId, '压缩文件夹失败:' . $result);
            $result = Tool::sendMsgToMail($address, [
                'title'     => '题库word文件-' . $examId . '-失败',
                'content'   => '压缩文件夹失败:' . $result . '<br>json数据：' . json_encode($tree, JSON_UNESCAPED_UNICODE),
                'html'      => true
            ]);
            $this->createMailErrLog($result);
            die;
        }
        $t2 = microtime(true);
        $result = Tool::sendMsgToMail($address, [
            'title'      => '题库word文件-' . $examId . '-成功',
            'content'    => '题库ID：' . $examId . '<br / >耗时：' . round($t2 - $t1, 3) . '秒',
            'attachment' => $path. '.zip',
            'html'       => true
        ]);
        $this->createMailErrLog($result);
        if($result !== true){
//            $result = Main::uploadToFileManageSystem($path . '.zip', 'zip', 'xhtest');
            $result = File::uploadOss($path . '.zip', 'res', 'questionBank')['url'];
            if($result){
                Main::createCommitLog('word', 'exam', 'export', $result, $examId, '上传文件服务器');
            }
        }
        Main::createCommitLog('word', 'exam', 'export', json_encode($tree, JSON_UNESCAPED_UNICODE), $examId, '导出题库');
        @unlink($path. '.zip');
        Tool::delDirAndFile($path);
        sleep(3);
        die('导出成功');
    }

    /**
     * 递归处理目录树
     *
     * @param $tree
     * @param $title
     *
     * create by ck 20170504
     */
    function dealTree(&$tree, &$title)
    {
        if(empty($title)) return;    //无数据则结束
        if(empty($tree)){
            foreach($title as $key => $val){
                if($val['ad_parentid'] == 0){
                    $tree[] = ['ad_id' => intval($val['ad_id']), 'ad_name' => $val['ad_name']];
                    unset($title[$key]);
                    $this->dealTree($tree, $title);
                }
            }
        }
        else{
            foreach($tree as $treeKey => $treeVal){
                foreach($title as $key => $val){
                    if($val['ad_parentid'] == $treeVal['ad_id']){
                        $tree[$treeKey]['oChild'][] = ['ad_id' => intval($val['ad_id']), 'ad_name' => $val['ad_name']];
                        unset($title[$key]);
                    }
                }
                if(isset($tree[$treeKey]['oChild'])) {
                    $this->dealTree($tree[$treeKey]['oChild'], $title);
                }
            }
        }
    }

    /**
     * 递归处理目录树，转为word
     *
     * @param $tree
     * @param Mysql $conn
     *
     * create by ck 20170504
     * modify by ck 20170525    增加处理阅读题小题
     */
    function dealWord(&$tree, Mysql $conn)
    {
        if(empty($tree)) return;    //无数据则结束
        foreach($tree as $treeKey => $treeVal){
            $sourceQuestionArr = $conn->fetchAll("select ho_zycontent as sQueContent,ho_zytype as iQueType,ho_answer as sAnswer,ho_id,ho_zytype from homework_list_base WHERE ho_parent_id = 0 and ho_ad_id = {$treeVal['ad_id']} order by ho_ord");
            $questionArr = [];
            foreach($sourceQuestionArr as $question){
                $questionArr[] = $question;
                if($question['ho_zytype'] == 6){
                    $childArr = $conn->fetchAll("select ho_zycontent as sQueContent,ho_zytype as iQueType,ho_answer as sAnswer from homework_list_base WHERE ho_parent_id = {$question['ho_id']} and ho_ad_id = {$treeVal['ad_id']} order by ho_ord");
                    foreach($childArr as $child){
                        $questionArr[] = $child;
                    }
                }
            }
            unset($sourceQuestionArr);
            if($questionArr){
                $url = $this->createWord($treeVal['ad_name'], $questionArr);
                if(!$url) {
                    $tree[$treeKey]['msg'] = '转换失败';
                    continue;
                }
                $tree[$treeKey]['url'] = $url;
            }
            if(isset($tree[$treeKey]['oChild'])) {
                $this->dealWord($tree[$treeKey]['oChild'], $conn);
            }
        }
    }

    /**
     * 转换为word
     *
     * @param $title
     * @param $questionArr
     * @return mixed
     *
     * create by ck 20170504
     */
    function createWord($title, $questionArr)
    {
        $show = $this->request->get('show', 'string');
        $imgBaseUrl = $this->getConfig()['imgBaseUrl'];
        $sleep = $this->request->getPost('sleep', 'int');
        if($sleep){
            sleep($sleep);
        }
        foreach($questionArr as $key => $question){
            $questionArr[$key]['sQueContent'] = str_replace('&gt;', '&amp;gt;', $questionArr[$key]['sQueContent']);
            $questionArr[$key]['sQueContent'] = str_replace('&lt;', '&amp;lt;', $questionArr[$key]['sQueContent']);
            preg_match_all("/<img.*?src=\"(\.\.\/.*?)\".*?>/i", $question['sQueContent'], $imgInfo);
            $imgInfo = end($imgInfo);
            if(!$imgInfo) continue;
            foreach($imgInfo as $src){
                $newSrc = str_replace('../', $imgBaseUrl . '/', $src);
                $questionArr[$key]['sQueContent'] = str_replace($src, $newSrc, $questionArr[$key]['sQueContent']);
            }
        }
        $data = [
            'compressionAlgorithm' => '',
            'docName' => $title,
            'documentType' => 'docx',
            'isCallback' => 1,
            'isCompress' => 2,
            'isProcessingStyle' => 1,
        ];
        foreach($questionArr as $question){
            $data['topics'][] = [
                'contents' => [
                    [
                        'content' => $question['sQueContent'] . ($question['iQueType'] == 1 ? '<p>答案：[答案始]'. $question['sAnswer'] . '[/答案终]</p>' : '')
                    ],
                ],
                'topicType' => 1
            ];
        }
        static $httpClient;
        if(empty($httpClient)){
            $httpClient = new HttpClient();
            $httpClient->setHeader('Content-Type', 'application/json');
        }
        $response = $httpClient->postJson($this->getConfig()['url'], $data);
        $body = $response->toObject();
        if($show){
            echo $title, ':', json_encode(['url' => $this->getConfig()['url'], 'data' => json_encode($data, JSON_UNESCAPED_UNICODE), 'response' => $body]);
        }
        return $body->status == 1000 ? $body->document->url : $body;
    }

    /**
     * 保存word到本地
     *
     * @param $tree
     * @param $path
     * @return bool
     *
     * create by ck 20170504
     */
    function saveWord($tree, $path)
    {
        foreach($tree as $treeKey => $treeVal){
            if(isset($treeVal['url'])){
                $fileName = rtrim($path, '/') . '/' . $treeVal['ad_name'] . '.doc';
                if(PATH_SEPARATOR==';'){
                    $fileName = iconv('utf-8', 'GBK', $fileName);
                }
                file_put_contents($fileName, file_get_contents($treeVal['url']));
            }
            if(isset($treeVal['oChild'])){
                $newPath = rtrim($path, '/') . '/' . $treeVal['ad_name'] . '/';
                $codePath = PATH_SEPARATOR == ';' ? iconv('utf-8', 'GBK', $newPath) : $newPath;
                if(is_dir($codePath) || mkdir($codePath, 0777, true)){
                    $this->saveWord($treeVal['oChild'], $newPath);
                }
            }
        }
        return true;
    }


    public function saveWordByJsonAction()
    {
        set_time_limit(0);
        $this->view->disable();
        $json = '';
        $tree = json_decode($json, true);
        $this->saveWord($tree,  'E:\\exam\\');
        die;
    }


}

